#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/times.h>
#include <sys/types.h>
#include <sys/wait.h>
#define null  NULL
#define HZ	100

void cpuio_bound(int last, int cpu_time, int io_time);

int main(int argc, char * argv[])
{
	pid_t pid1,pid2,pid3;
	pid1 = fork();
	if(pid1){
		printf("child1 is %d\n",pid1);
	}
	else{
		printf("child1 is here\n");
		cpuio_bound(5,2,1);	
	}

	pid2 = fork();
	if(pid2){
		printf("child2 is %d\n",pid2);
	}
	else{
		printf("child2 is here\n");
		cpuio_bound(5,1,2);	
	}

	pid3 = fork();
	if(pid3){
		printf("child3 is %d\n",pid3);
	}
	else{
		printf("child3 is here\n");
		cpuio_bound(5,4,0);	
	}
	
	wait(null);
	wait(null);
	wait(null);
	printf("father is %d\n",getpid());
	return 0;
}

void cpuio_bound(int last, int cpu_time, int io_time)
{
	struct tms start_time, current_time;
	clock_t utime, stime;
	int sleep_time;

	while (last > 0)
	{
		/* CPU Burst */
		times(&start_time);
		
		do
		{
			times(&current_time);
			utime = current_time.tms_utime - start_time.tms_utime;
			stime = current_time.tms_stime - start_time.tms_stime;
		} while ( ( (utime + stime) / HZ )  < cpu_time );
		last -= cpu_time;

		if (last <= 0 )
			break;

		/* IO Burst */
		
		sleep_time=0;
		while (sleep_time < io_time)
		{
			sleep(1);
			sleep_time++;
		}
		last -= sleep_time;
	}
}